// pages/spread/profit/profit.js
import * as API_Trade from '../../../api/trade.js'
import { Foundation } from '../../../ui-utils/index.js'
const app = getApp();
let that;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight: 0, // 滚动高度
    hideTip: false, // 提示隐藏
    years: [],
    months: [],
    days: [],
    member_id: '',
    // 收益列表
    profitList: [],
    // 检索条件
    typeActive: 0, // 账单类型
    typeActiveText: '日账单',
    start_time: '',
    end_time: '',
    showModal: false,
    modal_start_time: '',
    modal_end_time: '',
    activePicker: 0,
    time_picker: [],
    totalCount: {
      order_num: 0,
      show_order_price_sum: '¥0.0',
      show_commission_sum: '¥0.0'
    },
    // 商品分页
    page_no: 1,
    page_size: 10,
    page_count: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    this.computeHeight();
    // this.initDatas();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      profitList: [],
      totalCount: {
        order_num: 0,
        show_order_price_sum: '¥0.0',
        show_commission_sum: '¥0.0'
      },
      page_no: 1
    });
    this.initDefaultTime();
  },
  /**
    * @date 2020/06/15
    * @author wolfMan
    * @description {计算滚动高度}
  */
  computeHeight () {
    const that = this;
    wx.getSystemInfo({
      success: (res) => {
        let query = wx.createSelectorQuery();
        query.select('.top-fixed').boundingClientRect();
        query.select('.bottom-fixed').boundingClientRect();
        query.exec(response => {
          // let _height = res.windowHeight - response[1].height;
          that.setData({
            scrollHeight: res.windowHeight - response[0].height  - response[1].height + 'px'
          });
        });
      }
    });
  },
  /**
    * @date 2020/06/16
    * @author wolfMan
    * @description {显示账单类型弹层}
  */
  showTypeChange () {
    wx.showActionSheet({
      itemList: ['日账单', '月账单'],
      itemColor: '#000',
      success(res){
        if (res.tapIndex === 0){
          that.setData({
            typeActive: 0,
            typeActiveText: '日账单'
          });
        } else if (res.tapIndex === 1){
          that.setData({
            typeActive: 1,
            typeActiveText: '月账单'
          });
        };
        that.setData({
          profitList: []
        });
        that.initDefaultTime();
      }
    });
  },
  /**
    * @date 2020/06/16
    * @author wolfMan
    * @description {初始化默认显示时间}
  */
  async initDefaultTime () {
    const date = new Date();
    const nowYear = date.getFullYear();
    const nowMonth = date.getMonth() + 1;
    const nowDay = date.getDate();
    let { typeActive } = this.data;
    let startTime = '';
    let endTime = '';
    let startYearStr = nowYear;
    let startMonthStr = nowMonth;
    endTime = `${nowYear}-${await this.foundationStr(nowMonth)}`;
    if (typeActive === 1) {
      // 月账单 默认近半年
      let startMonth = nowMonth - 5;
      if (startMonth > 0) {
        startYearStr = nowYear;
        startMonthStr = await this.foundationStr(startMonth);
      } else {
        startYearStr = nowYear - 1;
        startMonthStr = await this.foundationStr(12 - Math.abs(startMonth));
      };
      startTime = `${startYearStr}-${startMonthStr}`;
    } else {
      // 日账单 默认近1个月
      endTime = `${endTime}-${await this.foundationStr(nowDay)}`;
      let startMonth = nowMonth - 1;
      if (startMonth > 0) {
        startYearStr = nowYear;
        startMonthStr = await this.foundationStr(startMonth);
      } else {
        startYearStr = nowYear - 1;
        startMonthStr = await this.foundationStr(12 - Math.abs(startMonth));
      };
      startTime = `${startYearStr}-${startMonthStr}-${await this.foundationStr(nowDay)}`;
    };
    this.setData({
      start_time: startTime,
      end_time: endTime,
      page_no: 1
    });
    this.getPageData();
  },
  /**
    * @date 2020/06/16
    * @author wolfMan
    * @description {初始化日期}
  */
  initDatas () {
    const date = new Date();
    const nowYear = date.getFullYear();
    const nowMonth = date.getMonth() + 1;
    const nowDay = date.getDate();
    // 循环前先清空数组
    let { years, months, start_time } = this.data;
    years = []
    months = []
    for (let i = nowYear - 10; i <= nowYear; i++) {
      years.push(i);
    };
    // 设置月份列表
    for (let i = 1; i <= 12; i++) {
      months.push(i);
    };
    this.setData({
      years,
      months
    });
    let startTime = start_time.split('-');
    this.getMonthDate(startTime[0], startTime[1], startTime[2]);
  },
  /**
    * @date 2020/06/16
    * @author wolfMan
    * @description {格式话月/日小于10}
  */
  foundationStr (num) {
    return num > 9 ? num : `0${num}`;
  },
  /**
    * @date 2020/06/16
    * @author wolfMan
    * @description {type~1:开始时间；2:结束时间 }
  */
  getMonthDate (year, month, day) {
    year = parseInt(year);
    month = parseInt(month);
    day = day ? parseInt(day) : day;
    let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    let dayNum = 0;
    // 通过年和月获取这个月份下有多少天
    if (month === 2) { // 闰年
      dayNum = ((year % 4 === 0) && ((year % 100) !== 0)) || (year % 400 === 0) ? 29 : 28;
    } else {
      dayNum = daysInMonth[month - 1];
    };
    let { typeActive, years, months, days, time_picker } = this.data;
    days = [];
    for (let i = 1; i <= dayNum; i++) {
      days.push(i)
    };
    this.setData({ days });
    // 初始 选中年月日对应下标
    let timePicker = [];
    // 获取滚动后 年月日对应的下标
    let yearIdx = years.indexOf(year);
    let monthIdx = months.indexOf(month);
    if (typeActive === 1) {
      timePicker = [yearIdx, monthIdx];
    } else {
      let dayIdx = day ? days.indexOf(day) : 0;
      timePicker = [yearIdx, monthIdx, dayIdx];
    };
    time_picker = timePicker;
    this.setData({
      // 重置滚动后 年月日 的下标
      time_picker
    });
  },
  /**
    * @date 2020/06/16
    * @author wolfMan
    * @description {时间滚动切换}
  */
  async timePickerChange (e) {
    // valIndex 是获取到的年月日在各自集合中的下标
    const valIndex = e.detail.value;
    const type = e.currentTarget.dataset.type;
    const { years, months, days, typeActive } = this.data;
    let year = years[valIndex[0]];
    let month = months[valIndex[1]];
    let day = days[valIndex[2]];
    // 滚动时显示对应选择项
    let _modalShowStr = `${year}-${await this.foundationStr(month)}`;
    if (typeActive !== 1) {
      _modalShowStr = `${_modalShowStr}-${await this.foundationStr(day)}`;
    };
    if (type === 1) {
      this.setData({
        modal_start_time: _modalShowStr
      });
    } else {
      this.setData({
        modal_end_time: _modalShowStr
      });
    };
    // 滚动时再动态 通过年和月获取 这个月下对应有多少天
    this.getMonthDate(year, month, day);
  },
  /**
    * @date 2020/06/15
    * @author wolfMan
    * @description {获取页面列表数据} 
  */
  getPageData () {
    let { typeActive, start_time, end_time, page_no, page_size, member_id } = this.data;
    member_id = wx.getStorageSync('user').member_id;
    let _params = {
      page_no,
      page_size,
      member_id,
      type: typeActive,
    };
    if (typeActive === 1) {
      _params.start_time = Foundation.dateToUnix(`${start_time}-01`);
      _params.end_time = Foundation.dateToUnix(`${end_time}-31`)
    } else {
      _params.start_time = Foundation.dateToUnix(start_time);
      _params.end_time = Foundation.dateToUnix(end_time)
    };
    API_Trade.getProfitList(_params).then(res => {
      const { data, data_total, page_size } = res.statisticPageList;
      const { order_num, show_commission_sum, show_order_price_sum } = res.statisticCount;
      let _pageCount = Math.ceil(data_total / page_size);
      let _profitList = this.data.profitList.concat(data);
      this.setData({
        profitList: _profitList,
        page_count: _pageCount,
        totalCount: {
          order_num: order_num || 0,
          show_order_price_sum: show_order_price_sum || '¥0.0',
          show_commission_sum: show_commission_sum || '¥0.0'
        }
      });
    });
  },
  /**
    * @date 2020/06/17
    * @author wolfMan
    * @description {加载更多}
  */
  loadMore: function () {
    let { page_no, page_count } = this.data;
    this.setData({ 
      page_no: page_no += 1
    });
    if (page_count >= page_no) {
      this.getPageData();
    };
  },
  /**
    * @date 2020/06/16
    * @author wolfMan
    * @description {关闭弹层}
  */
  hideTip () {
    this.setData({
      hideTip: true
    });
    this.computeHeight();
  },
  /**
    * @date 2020/06/16
    * @author wolfMan
    * @description {显示时间选择弹层}
  */
  showModal () {
    this.setData({
      modal_start_time: this.data.start_time,
      modal_end_time: this.data.end_time,
      activePicker: 1,
      showModal: true
    });
    that.initDatas();
  },
  /**
    * @date 2020/06/17
    * @author wolfMan
    * @description {切换需要选择的时间}
    * @params {1: 开始时间；2: 结束时间}
  */
  activePicker (e) {
    const _type = e.currentTarget.dataset.type;
    const { modal_start_time, modal_end_time } = this.data;
    let _activeTime = _type === 2 ? modal_end_time.split('-') : modal_start_time.split('-');
    this.getMonthDate(_activeTime[0], _activeTime[1], _activeTime[2], _type);
    this.setData({
      activePicker: _type
    });
  },
  /**
    * @date 2020/06/16
    * @author wolfMan
    * @description {关闭弹层}
  */
  closeModal () {
    this.setData({
      showModal: false
    });
  },
  /**
    * @date 2020/06/16
    * @author wolfMan
    * @description {弹层提交}
  */
  confirmModal () {
    let { modal_start_time, modal_end_time } = this.data;
    const modalStartTime =  Foundation.dateToUnix(modal_start_time);
    const modalEndTime =  Foundation.dateToUnix(modal_end_time);
    if (modalStartTime > modalEndTime) {
      wx.showToast({ title: '搜索的开始时间不能大于结束时间！', icon: 'none'});
      return;
    };
    this.setData({
      showModal: false,
      start_time: modal_start_time,
      end_time: modal_end_time,
      page_no: 1,
      page_count: 0
    });
    this.getPageData();
  },
  /**
    * @date 2020/08/11
    * @author wolfMan
    * @description {查看收益详情}
  */
  showDetail (e) {
    const { time } = e.currentTarget.dataset;
    const { typeActive } = this.data;
    wx.navigateTo({
      url: `/pages/spread/profit-detail/profit-detail?time=${time}&&type=${typeActive}`
    })
  }
})